package com.example.pokemon_chat_room;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.pokemon_chat_room.pojo.Msg;
import com.example.pokemon_chat_room.request.OkHttp;
import com.example.pokemon_chat_room.ui.notifications.NotificationsFragment;
import com.example.pokemon_chat_room.util.WebClient;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.example.pokemon_chat_room.databinding.ActivityMainBinding;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.Objects;

public class MainActivity extends AppCompatActivity {

    private ActivityMainBinding binding;

    private Dialog loginDialog;

    private Dialog regDialog;

    private String post = "";

    private OkHttp okHttp;

    private MyReceiver receiver;

    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getExtras().getString("error");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
                    openLoginDialog();
                }
            });
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        IntentFilter filter = new IntentFilter("com.example.pokemon_chat_room.EXPIRED");
        receiver = new MyReceiver();
        this.getApplicationContext().registerReceiver(receiver, filter);


        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);
        okHttp = new OkHttp();
        SharedPreferences mShared = getSharedPreferences("user", MODE_PRIVATE);
        SharedPreferences.Editor editor = mShared.edit();// 获得编辑器的对象


        String token = mShared.getString("token","");// 从共享参数中获得名叫name的字符串
        if (token.equals("")) {
            openLoginDialog();
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        JSONObject json = new JSONObject();
                        json.put("token", token);
                        JSONObject jsonObject = okHttp.Post(getApplicationContext(), "user/loginByToken", json);
                        Integer code = jsonObject.getInteger("code");
                        Looper.prepare();
                        if (code == 20007) {
                            Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                            WebClient.initWebSocket(MainActivity.this, token);
                        } else {
                            Toast.makeText(MainActivity.this, "登录状态过期，请重新登录", Toast.LENGTH_SHORT).show();
                            MainActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    openLoginDialog();
                                }
                            });

                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
        }





    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.getApplicationContext().unregisterReceiver(receiver);

    }

    public void openLoginDialog() {
        View alertDialogView = getLayoutInflater().inflate(R.layout.login_diaglog, null, false);
        TextView toRegBtn = alertDialogView.findViewById(R.id.tv_register);
        TextView username = alertDialogView.findViewById(R.id.et_user_name);
        TextView password = alertDialogView.findViewById(R.id.et_psw);
        Button loginBtn = alertDialogView.findViewById(R.id.btn_login);


        AlertDialog.Builder loginAlertDialog = new AlertDialog.Builder (MainActivity.this);
        loginAlertDialog
                .setView(alertDialogView)
                .setCancelable(false)
                .setTitle("登录页");

        loginDialog = loginAlertDialog.show ();


        toRegBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginDialog.dismiss();
                openRegDialog();
            }
        });

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject json = new JSONObject();
                            json.put("username", username.getText().toString());
                            json.put("password", password.getText().toString());
                            JSONObject jsonObject = okHttp.Post(getApplicationContext(),"user/login", json);
                            Integer code = jsonObject.getInteger("code");
                            String message = jsonObject.getString("message");
                            Looper.prepare();
                            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
                            if (code == 20007) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                System.out.println(data);
                                SharedPreferences mShared = getSharedPreferences("user", MODE_PRIVATE);
                                SharedPreferences.Editor editor = mShared.edit();// 获得编辑器的对象
                                editor.putString("token", data.getString("token"));// 添加一个名叫name的字符串参数
                                editor.putString("avatar", data.getString("avatar"));
                                editor.putString("username", data.getString("username"));
                                editor.putString("nickname", data.getString("nickname"));
                                editor.putString("amount", data.getString("amount"));
                                editor.putInt("grade", data.getInteger("grade"));
                                editor.apply();// 提交编辑器中的修改
                                WebClient.initWebSocket(MainActivity.this, data.getString("token"));
                                loginDialog.dismiss();
                            }
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }).start();
            }
        });
    }

    public void openRegDialog() {
        View alertDialogView = getLayoutInflater().inflate(R.layout.reg_dialog, null, false);
        TextView toLoginBtn = alertDialogView.findViewById(R.id.tv_register);
        Button reg_btn = alertDialogView.findViewById(R.id.btn_login);
        EditText et_user_name = alertDialogView.findViewById(R.id.et_user_name);
        EditText et_psw = alertDialogView.findViewById(R.id.et_psw);
        EditText et_psw_again = alertDialogView.findViewById(R.id.et_psw_again);




        AlertDialog.Builder loginAlertDialog = new AlertDialog.Builder (MainActivity.this);
        loginAlertDialog
                .setView(alertDialogView)
                .setCancelable(false)
                .setTitle("注册页");


        regDialog = loginAlertDialog.show ();


        toLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                regDialog.dismiss();
                openLoginDialog();
            }
        });

        reg_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!et_psw_again.getText().toString().equals(et_psw.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "两次密码不一致", Toast.LENGTH_SHORT).show();
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject json = new JSONObject();
                            json.put("username", et_user_name.getText().toString());
                            json.put("password", et_psw.getText().toString());
                            JSONObject jsonObject = okHttp.Post(getApplicationContext(),"user/register", json);
                            Integer code = jsonObject.getInteger("code");
                            String message = jsonObject.getString("message");
                            Looper.prepare();
                            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();

                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                }).start();
            }
        });
    }

}